package com.ch.engine.utils.aes3;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
import java.util.Base64;

public class AESWithSaltExample {
    public static void main(String[] args) throws Exception {
        String password = "mySecretPassword";
        String plaintext = "Hello, AES with salt!";

        // 生成随机盐值
        byte[] salt = new byte[16];
        SecureRandom random = new SecureRandom();
        random.nextBytes(salt);

        // 派生 AES 密钥
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
        SecretKey secretKey = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");

        // 生成随机初始向量（IV）
        byte[] iv = new byte[16];
        random.nextBytes(iv);
        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        // 加密
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        byte[] ciphertext = cipher.doFinal(plaintext.getBytes());

        // 输出加密结果
        System.out.println("Salt: " + Base64.getEncoder().encodeToString(salt));
        System.out.println("IV: " + Base64.getEncoder().encodeToString(iv));
        System.out.println("Ciphertext: " + Base64.getEncoder().encodeToString(ciphertext));
    }
}
